#    Author: Indranil Ghosh
#    This code written in python (version 2.7) with the help of pygame module generates the Sierpinski's gasket
#    Method: Click on the display surface on 4 random places to mark the vertices of the triangle and any random starting point from where the plotting of the next points begin. After a number of iterations (wait for few seconds) the Sierpinski's gasket gets drawn on the screen  
    


import random, pygame, sys
from pygame.locals import *

#set up the window
DISPLAYSURF=pygame.display.set_mode((1000, 800), 0, 32)
pygame.display.set_caption('Sierpinski Triangle')

#set up the colors
BLACK=(0, 0, 0)
WHITE=(255, 255, 255)

i=0
#run the game loop
while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()
        elif event.type==MOUSEBUTTONUP:
            i+=1
            if i==1:
                A=(event.pos[0], event.pos[1])
                pygame.draw.circle(DISPLAYSURF, WHITE, A,  2, 0)
            elif i==2:
                B=(event.pos[0], event.pos[1])
                pygame.draw.circle(DISPLAYSURF, WHITE, B,  2, 0)
            elif i==3:
                C=(event.pos[0], event.pos[1])
                pygame.draw.circle(DISPLAYSURF, WHITE, C,  2, 0)
            elif i==4:
                St=(event.pos[0], event.pos[1])
                pygame.draw.circle(DISPLAYSURF, WHITE, St,  2, 0)
            else:
                pygame.quit()
                sys.exit()
    if i==4:
        x=random.randint(1, 6)
        if x==1 or x==2: St=((St[0] + A[0])/2, (St[1] + A[1])/2)
        elif x==3 or x==4: St=((St[0] + B[0])/2, (St[1] + B[1])/2)
        else: St=((St[0] + C[0])/2, (St[1] + C[1])/2)   
        pygame.draw.circle(DISPLAYSURF, WHITE, St, 2, 0)
    pygame.display.update()



